﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.AnalysisServices;

namespace ParallelCubeProcessor
{
    class ThreadHandler : ParallelProcessingHandler
    {
        private int _maxConcurrentThreads;
        private string _serverName;
        private System.Collections.Generic.List<Thread> _threads = new System.Collections.Generic.List<Thread>();

        private int ActiveThreads
        {
            get
            {
                int activeThreads = 0;
                foreach (Thread t in _threads)
                {
                    if (t.IsAlive)
                    {
                        activeThreads++;
                    }
                }
                return activeThreads;
            }
        }

        public ThreadHandler(int MaxConcurrentThreads, string ServerName)
        {
            _maxConcurrentThreads = MaxConcurrentThreads;
            _serverName = ServerName;
        }

        public void ProcessDatabase(Database DB)
        {
            while (ActiveThreads >= _maxConcurrentThreads)
            {
                Thread.Sleep(500);
            }

            CubeProcessingThread cpt = new CubeProcessingThread(_serverName);
            Thread cptThread = new Thread(cpt.Start);
            cptThread.Start(DB);
            _threads.Add(cptThread);
        }
        public void FinishProcessing()
        {
            while (ActiveThreads > 0)
            {
                Thread.Sleep(500);
            }
        }
    }
}
